﻿using HUNTERS.CORE;
using HUNTERS.SERVER.Models;
using log4net;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HUNTERS.SERVER
{
    public class Server
    {
        private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private Thread _thread;
        private UdpClient udpClient; 
        private IPEndPoint remoteIpEndPoint; 
        private byte[] receivedBytes;
        public static Action<Server, MessageEventArgs> OnEvent;

        public void StartServer(int port)
        {
            udpClient = new UdpClient(port);
            _thread = new Thread(StartThreadServer);
            _thread.Start();
        }


        private void StartThreadServer()
        {
            try
            {
                remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

                while (true)
                {
                    receivedBytes = udpClient.Receive(ref remoteIpEndPoint);
                    var data = Encoding.ASCII.GetString(receivedBytes).ToString().Trim();
                    if (data.Length > 0)
                    {
                        var receivedData = Core.Decrypt(data).Trim();
                        if (JSONValidate(receivedData))
                        {
                            MsgSend(receivedData);
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                logger.Error(ex.Message);
            }
        }

        public void StopServer()
        {
            udpClient.Close();
            if (_thread != null && _thread.IsAlive)
            {
                _thread.Abort();
            }
        }

        private void MsgSend(string msg)
        {
            OnEvent?.Invoke(this, new MessageEventArgs(msg));
        }

        private bool JSONValidate(string json)
        {
            try
            {
                JsonConvert.DeserializeObject<Upload>(json);
                return true;
            }
            catch(Exception ex)
            {
                logger.Error(ex.Message);
                return false;
            }
        }
    }
}
